package gui

import (
	"fmt"
	"pass-tree/internal/gui/windows"
	"pass-tree/internal/logic/models"
	"pass-tree/pkg/utils"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

type TableUI struct {
	TableRef         *widget.Table
	DetailsBtn       *widget.Button
	DouFuJingLingBtn *widget.Button
	CopyBtn          *widget.Button
	EditBtn          *widget.Button
	DeleteBtn        *widget.Button
	AutoGetInfoBtn   *widget.Button
}

var tableUI TableUI

// 创建表格界面
func (ui *MainWindow) MakeTableUI(win fyne.Window, name string, list []models.Password) fyne.CanvasObject {
	// 定义表头
	headers := []string{"名称", "用户名", "密码", "描述", "状态", "操作"}
	// 获取表格数据
	/* data := [][]string{
		// {"名称", "用户名", "密码", "描述", "状态"}, //表头
		{"微信小程序", "0", "审核失败", "0", "0"},
		{"审核中", "0", "审核通过", "0", "0"},
		{"审核通过(备案中)", "0", "升级中", "0", "0"},
		{"已下架", "0", "其他", "0", "0"},
		{"全部", "0", "", "", "0"},
	} */
	t := widget.NewTableWithHeaders(
		func() (int, int) {
			// 返回行数 和 列数
			return len(list), len(headers)
		},
		func() fyne.CanvasObject {
			// 创建一个新的单元格对象
			// return widget.NewLabel("")
			// 所有单元格默认创建空容器，实际内容在UpdateCell中处理
			return container.NewHBox()
		},
		func(id widget.TableCellID, cell fyne.CanvasObject) {
			container := cell.(*fyne.Container)
			// 清空容器原有内容
			container.Objects = nil
			if id.Col == -1 {
				container.Add(widget.NewLabel(""))
				// 隐藏行号列
				return
			}
			if id.Col == len(headers)-1 {
				// 最后一列(操作列)
				// 表头单元格
				// 添加操作按钮
				//通过rpa自动从网页中获取信息
				tableUI.AutoGetInfoBtn = widget.NewButton("自动获取信息", func() {

					ui.Services.RpaAutoWebObtainInfo("username", "password")

				})

				tableUI.DetailsBtn = widget.NewButton("详情", func() {

					content := ui.Services.FormatDetails(list[id.Row])
					// 显示详情
					showDetailsWindow(content)

				})

				tableUI.DouFuJingLingBtn = widget.NewButton("导入抖服", func() {
					cnf := dialog.NewConfirm("提示", "您是否要导入到抖服版本精灵中?", func(response bool) {
						if response {
							if list[id.Row].CustomContent != nil {
								var appid string
								for _, v := range list[id.Row].CustomContent {
									if v.Input_type == "appid" {
										appid = v.Content
									}
								}
								if appid == "" {
									dialog.ShowInformation("提示", "请先设置appid", win)
									return
								}
								ui.Services.ImportToDoufu(list[id.Row].Name, appid)
							}
						}
					}, win)
					cnf.SetDismissText("取消")
					cnf.SetConfirmText("确认")
					cnf.Show()
				})
				//复制
				tableUI.CopyBtn = widget.NewButton("", func() {

					content := ui.Services.FormatDetails(list[id.Row])
					// 复制到剪贴板
					utils.CopyText(content)
					// 显示提示（可选）
					showCopyNotification(content)
				})
				tableUI.CopyBtn.Icon = theme.ContentCopyIcon()

				tableUI.EditBtn = widget.NewButton("编辑", func() {
					// fmt.Printf("正在编辑第%d行: %+v\n", id.Row+1, list[id.Row])
				})
				tableUI.EditBtn.OnTapped = windows.ShowEditWindow(list[id.Row], func() {
					// 编辑完成后刷新列表
					ui.GetList()
					if t, ok := TreeTabData[name]; ok {
						setTreeTab(t)
					}
				})

				tableUI.DeleteBtn = widget.NewButton("删除", func() {
					// fmt.Printf("正在删除第%d行: %+v\n", id.Row+1, list[id.Row])
					cnf := dialog.NewConfirm("提示", "您是否要删除'"+list[id.Row].Name+"'?", func(response bool) {
						if response {
							// 删除数据
							ui.Services.DeletePassword(list[id.Row].Id)
							ui.GetList()
							if t, ok := TreeTabData[name]; ok {
								setTreeTab(t)
							}
						}
					}, win)
					cnf.SetDismissText("取消")
					cnf.SetConfirmText("确认")
					cnf.Show()
				})

				container.Add(tableUI.AutoGetInfoBtn)
				container.Add(tableUI.DetailsBtn)
				container.Add(tableUI.DouFuJingLingBtn)
				container.Add(tableUI.CopyBtn)
				container.Add(tableUI.EditBtn)
				container.Add(tableUI.DeleteBtn)

			} else {
				// cell.(*widget.Label).SetText(list[id.Row][id.Col].Name)
				// cell.(*widget.Label).Alignment = fyne.TextAlignCenter

				// 数据列
				// 根据列索引显示不同数据
				label := widget.NewLabel("")
				row := list[id.Row]
				switch id.Col {
				case 0:
					// o.(*fyne.Container).Objects[1].(*widget.Label).SetText(statusText)
					label.SetText(utils.Substring(row.Name, 0, 9))
				case 1:
					// label.SetText(fmt.Sprintf("%d", row.Age))
					label.SetText(utils.Substring(row.Username, 0, 6))
				case 2:
					label.SetText(utils.Substring(row.Password, 0, 6))
				case 3:
					label.SetText(utils.Substring(row.Desc, 0, 6))
				case 4:
					// label.SetText(fmt.Sprintf("%d", row.Status))
					if row.Status == 0 {
						label.SetText("正常")
					}
				}
				container.Add(label)
			}
		},
	)
	tableUI.TableRef = t // 保存引用
	// 设置表头
	t.UpdateHeader = func(id widget.TableCellID, template fyne.CanvasObject) {
		if id.Col == -1 {
			if label, ok := template.(*widget.Label); ok {
				label.SetText("")
			}
			return // 完全跳过行号列
		}
		if id.Col < 0 || id.Col >= len(headers) {
			return
		}
		if label, ok := template.(*widget.Label); ok {
			label.SetText(headers[id.Col])
		}
	}
	/* // 添加右键菜单
	t.OnTappedSecondary = func(pe *fyne.PointEvent) {
		id := table.GetSelected()
		if id.Row == -1 {
			return
		}

		content := data[id.Row][id.Col]

		menu := fyne.NewMenu("",
			fyne.NewMenuItem("复制", func() {
				clipboard := fyne.CurrentApp().Driver().(desktop.Driver).Clipboard()
				clipboard.SetContent(content)
				showCopyNotification(content)
			}),
		)

		widget.ShowPopUpMenuAtPosition(menu, fyne.CurrentApp().Driver().CanvasForObject(table), pe.AbsolutePosition)
	} */
	// 添加点击复制功能
	t.OnSelected = func(id widget.TableCellID) {
		if id.Row == -1 { // 忽略表头点击
			return
		}

		// if id.Col == len(headers)-1 { // 忽略操作列点击
		// 	return
		// }

		// 获取单元格内容

		var content string
		row := list[id.Row]
		switch id.Col {
		case 0:
			content = row.Name
		case 1:
			content = row.Username
		case 2:
			content = row.Password
		case 3:
			content = row.Desc
		case 4:
			content = fmt.Sprintf("%d", row.Status)
		}

		// 复制到剪贴板
		/* clipboard := fyne.CurrentApp().Driver().(desktop.Driver).Clipboard()
		clipboard.SetContent(content) */
		utils.CopyText(content) // 调用复制函数

		// 显示提示（可选）
		showCopyNotification(content)
	}

	// 隐藏行号列
	t.SetColumnWidth(-1, 0) // 将序号列宽度设为0
	// 设置其他列宽
	for i := 0; i < len(headers); i++ {
		if i == len(headers)-1 {
			// 操作列宽度
			t.SetColumnWidth(i, 245)
		} else if i == len(headers)-2 {
			t.SetColumnWidth(i, 70)
		} else if i == 0 {
			t.SetColumnWidth(i, 130)
		} else {
			t.SetColumnWidth(i, 105)
		}
	}

	// 设置行高
	/* t.SetRowHeight(2, 30) // 所有行高设为30像素 */
	t.Refresh() // 必须调用Refresh更新显示

	return t
}

// 显示复制成功的提示（可选）
func showCopyNotification(content string) {
	window := fyne.CurrentApp().NewWindow("复制成功")
	window.SetContent(widget.NewLabel("已复制:\n" + content))
	window.Resize(fyne.NewSize(220, 100))
	window.Show()

	// 3秒后自动关闭
	time.AfterFunc(3*time.Second, func() {
		window.Close()
	})
}

// 显示详情窗口
func showDetailsWindow(content string) {
	window := fyne.CurrentApp().NewWindow("详情")
	contentLabel := widget.NewLabel(content)
	copyAllBtn := widget.NewButton("复制验证码文字", func() {})
	toVerifyCodeBtn := widget.NewButton("复制验证码文字", func() {})
	configInfoBtn := widget.NewButton("复制后台配置信息", func() {})
	bodyLayout := container.New(layout.NewVBoxLayout(), contentLabel, copyAllBtn, toVerifyCodeBtn, configInfoBtn)
	window.SetContent(bodyLayout)
	window.Resize(fyne.NewSize(470, 400))
	window.CenterOnScreen()
	window.Show()
}
